﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ConfigLibrary;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace ConfigGenerator
{
	public partial class ConfigGenerator : Form
	{

		#region CTOR
		public ConfigGenerator()
		{
			InitializeComponent();

			config = new Config();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			configFile = String.Empty;
			label13.Hide();
			label17.Hide();
			label18.Hide();
			ToggleEnabled(true);
		}
		#endregion

		#region Private Fields
		private Config config;
		private string configFile;
		private bool configChanged;
		private	string mailhost;
		private	string mailname;
		private	string mailpass;
		private	int port;
		private	string sqlpass;
		private	string sqlhost;
		private	string sqlname;
		private	int sqlport;
		private	string sqldata;
		private string folderwatch;
		private string folderwrite;
		private string datahost;
		private int serverport;
		private int clientport;
        private string eddsname;
        private string eddspass;
        private string qbname;
        private string qbpass;
		private bool SSL;
		private bool logon;
		private bool autoget;
		private bool autosync;
		#endregion

		#region Event Handlers
		/// <summary>
		/// Prompts the user to enter the filename of the new settings file to create
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void newConfigToolStripMenuItem_Click(object sender, EventArgs e)
		{
			SaveFileDialog diag = new SaveFileDialog();
			diag.OverwritePrompt = true;
			if (diag.ShowDialog() == DialogResult.OK)
			{
				configFile = diag.FileName;
				config = new Config();
				config.SaveConfig(configFile);
				BindConfigInfo();
				UpdateTitle();
				configChanged = false;
			}

			ToggleEnabled(true);
		}

		/// <summary>
		/// Prompts user to select an existing config file, and then opens it.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void openConfigToolStripMenuItem_Click(object sender, EventArgs e)
		{
			OpenFileDialog diag = new OpenFileDialog();
			diag.Multiselect = false;

			if (diag.ShowDialog() == DialogResult.OK)
			{

				configFile = diag.FileName;
				Stream s = File.Open(configFile, FileMode.Open);
				BinaryFormatter b = new BinaryFormatter();
				config = (Config)b.Deserialize(s);


				s.Close();

				BindConfigInfo();
				UpdateTitle();
				configChanged = false;
			}

			ToggleEnabled(true);

		}

		/// <summary>
		/// Prompts user to specify the name of the folder to monitor
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void browseButton_Click(object sender, EventArgs e)
		{
			FolderBrowserDialog diag = new FolderBrowserDialog();
			if (diag.ShowDialog() == DialogResult.OK)
			{
				WatchedFolderBox.Text = diag.SelectedPath;
			}
		}

		private void WriteFileBrowse_Click(object sender, EventArgs e)
		{
			FolderBrowserDialog diag = new FolderBrowserDialog();
			if (diag.ShowDialog() == DialogResult.OK)
			{

				WriteFolderBox.Text = diag.SelectedPath;
			}
		}

		/// <summary>
		/// Saves the config settings to the current file
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void saveBtn_Click(object sender, EventArgs e)
		{
			if (MailPassword1.Text != String.Empty)
			{
				if (MailPassword2.Text == String.Empty)
				{
					MessageBox.Show("You must verify your password before you can save.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}

				if (!MailPassword1.Text.Equals(MailPassword2.Text))
				{
					MessageBox.Show("Mail Server Passwords do not match", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}
				if (!SqlPasswordBox1.Text.Equals(SqlPasswordBox2.Text))
				{
					MessageBox.Show("Sql Server Passwords do not match", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}
			}

			SaveSettings();
			config.SaveConfig(configFile);
			MessageBox.Show("Settings saved successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
			configChanged = false;
		}

		/// <summary>
		/// Closes the application, prompting the user to save changes if any values have been changed since the last save
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void closeBtn_Click(object sender, EventArgs e)
		{
			if (configChanged)
			{
				DialogResult res = MessageBox.Show("The current configuration has been changed, would you like to save it?", "Save Changes?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
				switch (res)
				{
					case DialogResult.Yes:
						{
							SaveSettings();
							config.SaveConfig(configFile);
							break;
						}
					case DialogResult.No:
						{

							break;
						}
					case DialogResult.Cancel:
						{

							return;
						}
				}
			}
			this.Close();
		}
		#endregion

		#region Helper Method
		/// <summary>
		/// Update the title bar to reflect the currently open settings file
		/// </summary>
		public void UpdateTitle()
		{
			this.Text = String.Format("Configuration Editor - {0}", configFile);

		}

		/// <summary>
		/// Must be called prior to calling config.SaveConfig().
		/// </summary>
		private void SaveSettings()
		{

			config.AddFileMonitorPaths(WatchedFolderBox.Text, WriteFolderBox.Text);
			config.AddMailInfo(MailHostName.Text, MailUserName.Text, MailPassword2.Text, port);
			config.AddSqlInfo(SqlHostBox.Text, SqlUserNameBox.Text, SqlPasswordBox2.Text, SqlDatabaseBox.Text, sqlport);
			config.AddDataInfo(DataHostbox.Text, serverport, clientport);
            config.AddEddsInfo(EddsUserNameBox.Text, EddsPasswordBox2.Text);
            config.AddQbInfo(QbUserNameBox.Text, QbPasswordBox2.Text);
		}

		/// <summary>
		/// Sets the state of the controls. Used to turn the controls on once a config file is specified
		/// </summary>
		/// <param name="state"></param>
		public void ToggleEnabled(bool state)
		{
			MailHostName.Enabled = state;
			MailUserName.Enabled = state;
			MailPassword1.Enabled = state;
			MailPassword2.Enabled = state;
			SqlHostBox.Enabled = state;
			SqlUserNameBox.Enabled = state;
			SqlPasswordBox1.Enabled = state;
			SqlPasswordBox2.Enabled = state;
			SqlDatabaseBox.Enabled = state;
			WatchedFolderBox.Enabled = state;
			WatchedFolderButton.Enabled = state;
			useSSL.Enabled = state;
			autoLogon.Enabled = state;
			autoLoad.Enabled = state;
			saveBtn.Enabled = state;
			WriteFolderBox.Enabled = state;
			WriteFileBrowse.Enabled = state;
			autoSyncCacheBox.Enabled = state;
			MailPortBox.Enabled = state;
			SqlPortBox.Enabled = state;
            EddsUserNameBox.Enabled = state;
            EddsPasswordBox1.Enabled = state;
            EddsPasswordBox2.Enabled = state;
            QbUserNameBox.Enabled = state;
            QbPasswordBox1.Enabled = state;
            QbPasswordBox2.Enabled = state;
		}
		#endregion

		#region Bind Methods
		/// <summary>
		/// Updates the values of the controls with the currently loaded config object
		/// </summary>
		public void BindConfigInfo()
		{

			config.GetMailInfo(out mailhost, out mailname, out mailpass, out port);
			MailHostName.Text = mailhost;
			MailUserName.Text = mailname;
			MailPassword1.Text = mailpass;
			MailPassword2.Text = mailpass;
			MailPortBox.Text = port.ToString();			

			config.GetSqlInfo(out sqlhost, out sqlname, out sqlpass, out sqldata, out sqlport);
			SqlHostBox.Text = sqlhost;
			SqlUserNameBox.Text = sqlname;
			SqlPasswordBox1.Text = sqlpass;
			SqlPasswordBox2.Text = sqlpass;
			SqlDatabaseBox.Text = sqldata;
			SqlPortBox.Text = sqlport.ToString();

            config.GetEddsInfo(out eddsname, out eddspass);
            EddsUserNameBox.Text = eddsname;
            EddsPasswordBox1.Text = eddspass;
            EddsPasswordBox2.Text = eddspass;

            config.GetQbInfo(out qbname, out qbpass);
            QbUserNameBox.Text = qbname;
            QbPasswordBox1.Text = qbpass;
            QbPasswordBox2.Text = qbpass;

			config.GetFileMonitorPaths(out folderwatch, out folderwrite);
			WatchedFolderBox.Text = folderwatch;
			WriteFolderBox.Text = folderwrite;

			config.GetDataInfo(out datahost, out serverport, out clientport);
			DataHostbox.Text = datahost;
			ServerPortbox.Text = serverport.ToString();
			ClientPortbox.Text = clientport.ToString();

			useSSL.Checked = false;
			autoLogon.Checked = true;
			autoLoad.Checked = true;
			autoSyncCacheBox.Checked = false;
			configChanged = false;

		}
		#endregion

		#region Update Events
		private void hostName_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
			mailhost = MailHostName.Text;
		}

		private void usernameBox_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
			mailname = MailUserName.Text;
		}

		private void passwordBox_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
		}

		private void passwordBox2_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
		}

		private void SqlHostBox_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
			sqlhost = SqlHostBox.Text;
		}

		private void WatchedFolderBox_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
			folderwatch = WatchedFolderBox.Text;
		}

		private void useSSL_CheckedChanged(object sender, EventArgs e)
		{
			configChanged = true;
			SSL = useSSL.Checked;
		}

		private void autoLogon_CheckedChanged(object sender, EventArgs e)
		{
			configChanged = true;
			logon = autoLogon.Checked;
		}

		private void autoLoad_CheckedChanged(object sender, EventArgs e)
		{
			configChanged = true;
			autoget = autoLoad.Checked;
		}

		private void autoSyncCacheBox_CheckedChanged(object sender, EventArgs e)
		{
			configChanged = true;
			autosync = autoSyncCacheBox.Checked;
		}

		private void WriteFolderBox_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
			folderwrite = WriteFolderBox.Text;
		}

		private void MailPortBox_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
			try
			{
				port = int.Parse(MailPortBox.Text);
				label13.Hide();
			}
			catch (FormatException ex)
			{
				label13.ForeColor = Color.Red;
				label13.Show();
			}
		}

		private void SqlUserNameBox_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
		}

		private void SqlDatabaseBox_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
		}

		private void SqlPasswordBox1_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
		}

		private void SqlPasswordBox2_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
		}

        private void EddsUserNameBox_TextChanged(object sender, EventArgs e)
        {
            configChanged = true;
        }

        private void EddsPasswordBox1_TextChanged(object sender, EventArgs e)
        {
            configChanged = true;
        }

        private void EddsPasswordBox2_TextChanged(object sender, EventArgs e)
        {
            configChanged = true;
        }
		
		private void DataHostbox_TextChanged(object sender, EventArgs e)
		{
			configChanged = true;
		}

        private void QbUserNameBox_TextChanged(object sender, EventArgs e)
        {
            configChanged = true;
        }

        private void QbPasswordBox1_TextChanged(object sender, EventArgs e)
        {
            configChanged = true;
        }

        private void QbPasswordBox2_TextChanged(object sender, EventArgs e)
        {
            configChanged = true;
        }

		private void ServerPortbox_TextChanged(object sender, EventArgs e)
		{

			configChanged = true;
			try
			{
				serverport = int.Parse(ServerPortbox.Text);
				label17.Hide();
			}
			catch (FormatException ex)
			{
				label17.ForeColor = Color.Red;
				label17.Show();
			}
		}

		private void ClientPortbox_TextChanged(object sender, EventArgs e)
		{

			configChanged = true;
			try
			{
				clientport = int.Parse(ClientPortbox.Text);
				label18.Hide();
			}
			catch (FormatException ex)
			{
				label18.ForeColor = Color.Red;
				label18.Show();
			}
		}
		
		private void SqlPortBoxTextChanged(object sender, EventArgs e)
		{
			configChanged = true;
			try {
				sqlport = int.Parse(SqlPortBox.Text);
				label20.Hide();
			} catch (FormatException ex) {
				label20.ForeColor = Color.Red;
				label20.Show();
			}
		}
		#endregion

       

        

	}
}